const {usernameReg,passwordReg,nicknameReg} = require('../config');
const {tableModel} = require('../db');

async function loginHandler(req,res,next){
 
    const {username,password} = req.body;


    //如果用户没填写用户名或者密码 报错 
    if(!username || !password){
        return next(4);
    }

    const info = await tableModel.findOne({username,password})

    // console.log(info)// 如果登录成功  info 返回一个对象  失败 null

    // res.send({
    //     code:info?1:0,
    //     message:info?'登录成功':'登录失败'
    // })
    if(info){
        res.send({
            code:1,
            message:'登录成功',
            id:info['_id'],
            token:'sadfasdfsadfasdfasdf'
        })
    }
    else{
        res.send({
            code:0,
            message:'登录失败'
        })
    }


}


async function registerHandler(req,res,next){

    const {username,password,rpassword,nickname} = req.body;
    console.log(username,password,rpassword,nickname);
    const flag  = await tableModel.findOne({username})
    console.log(flag);
    if(flag){
        res.send({
            code:0,
            message:'该用户名已经存在'
        })
    }

    if(password !==rpassword){
        return next(6);
    }

    if(!usernameReg.test(username) ||!passwordReg.test(password) || !nicknameReg.test(nickname)){
        return next(5)
    }

    await new tableModel({
        username,
        password,
        nickname
    }).save()

    res.send({
        code:1,
        message:'注册成功'
    })

}


module.exports = {
    loginHandler,
    registerHandler
}